package com.hxci.pointmap.controller;

import com.hxci.pointmap.service.LoginService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求编码
        req.setCharacterEncoding("UTF-8");
        
        // 设置响应编码和内容类型
        resp.setContentType("application/json;charset=UTF-8");
        
        // 打印所有请求参数，用于调试
        System.out.println("=== 请求参数 ===");
        req.getParameterMap().forEach((key, values) -> {
            System.out.println(key + ": " + String.join(", ", values));
        });
        
        LoginService loginService = new LoginService();
        String checkResult = loginService.checkLogin(req, resp);
        
        System.out.println("checkResult: " + checkResult);
        
        // 创建响应对象
        Map<String, Object> responseMap = new HashMap<>();
        
        if("success".equals(checkResult)){
            // 登录成功
            responseMap.put("success", true);
            responseMap.put("message", "登录成功");
            responseMap.put("redirectUrl", "main.jsp");
        }
        else{
            // 登录失败，获取错误信息
            String errorMessage = (String) req.getAttribute("errorMessage");
            if (errorMessage == null) {
                errorMessage = "登录失败，请检查用户名、密码和验证码";
            }
            
            responseMap.put("success", false);
            responseMap.put("message", errorMessage);
        }
        
        // 将响应对象转换为JSON字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonResponse = objectMapper.writeValueAsString(responseMap);
        
        // 输出JSON响应
        PrintWriter out = resp.getWriter();
        out.print(jsonResponse);
        out.flush();
    }
}
